import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author YuanYuan
 * @Date 2022/11/28
 * @Time 14:46
 */
@WebServlet("/submit")
public class SubmitServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession httpSession = req.getSession(false);
        if(null == httpSession) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }
        User user = (User) httpSession.getAttribute("user");
        if(null == user) {
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户未登录");
            return;
        }

        String title = req.getParameter("title");
        String content = req.getParameter("content");
        int userId = user.getUserId();

        Blog blog = new Blog();
        blog.setUserId(userId);
        blog.setTitle(title);
        blog.setContent(content);

        try {
            BlogDAO.insert(blog);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        resp.setStatus(302);
        resp.sendRedirect("blog_list.html");
    }
}
